#include "mm.h"
#include "sysregs.h"
#include "task.h"

.section  .rodata
.align 3
.globl string1
string1:
	.string "Booting at EL"

.align 3
.globl sp_addr
sp_addr:
	.quad init_task_union+4096-8

.section ".text.boot"

.globl _start
_start:
	mrs	x0, mpidr_el1		
	and	x0, x0,#0xFF		// 检查处理器核心ID
	cbz	x0, master		// 除了CPU0，其他CPU都会在这里死循环等待
	b	proc_hang

proc_hang: 
	b 	proc_hang

master:
	mrs x5, CurrentEL
	cmp x5, #CurrentEL_EL3
	b.eq el3_entry
	b el2_entry

el3_entry:
	bl print_el

	// just for el3
	ldr x0, =SCR_VALUE
	msr scr_el3, x0

	// for el2
	ldr x0, =HCR_RW
	msr hcr_el2, x0	

	ldr x0, =SCTLR_EL2_VALUE_MMU_DISABLED
	msr sctlr_el2, x0

	ldr x0, =SPSR_EL2
	msr spsr_el3, x0

	adr x0, el2_entry
	msr elr_el3, x0

	eret

el2_entry:
	bl print_el

	// again for el2
	ldr x0, =HCR_RW
	msr hcr_el2, x0

	ldr x0, =SCTLR_EL1_VALUE_MMU_DISABLED
	msr sctlr_el1, x0

	ldr x0, =SPSR_EL1
	msr spsr_el2, x0

	adr x0, el1_entry
	msr elr_el2, x0

	eret

el1_entry:
	bl print_el
	/* 设置异常向量表基地址到vbar寄存器 */
	ldr     x5, =vectors
	msr     vbar_el1, x5
	isb

	adr x0, bss_begin
	adr x1, bss_end
	sub x1, x1, x0
	bl memzero

	bl init_page
	bl enable_mmu

.global mmu_enabled
mmu_enabled:
	ldr x0, =sp_addr
	ldr x1, [x0]
	mov sp, x1
	
	bl  kernel_main
	b   proc_hang // should never come here

print_el:
	ret
	mov x10, x30

	/* print EL */
	ldr x0, =string1
	bl put_string_uart

	mrs x5, CurrentEL
	/* get the currentEL value */
	lsr x2, x5, #2
	mov x0, #48
	add x0, x0, x2
	bl put_uart
	/* print the new line tab */
	mov x0, #10
	bl put_uart

	mov x30, x10
	ret

	.global trigger_alignment
	trigger_alignment:
        ldr x0, =0x80002
        ldr x1, [x0]
        ret  
